package com.os.ordersystem.controller;

import com.os.ordersystem.bean.Food;
import com.os.ordersystem.bean.OrderItem;
import com.os.ordersystem.bean.Page;
import com.os.ordersystem.bean.ResultDTO;
import com.os.ordersystem.service.FoodService;
import com.os.ordersystem.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.channels.SelectableChannel;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/food")
public class FoodController {

    @Autowired
    private FoodService foodService;

    @Autowired
    private OrderItemService orderItemService;

    //添加食品
    @PostMapping("/add")
    public ResultDTO addFood(@RequestBody Food food) {
        food.setStatus(1);
        int i = foodService.addFood(food);
        return ResultDTO.success();
    }

    //删除食品
    @DeleteMapping("/del")
    public ResultDTO delFoodById(@RequestParam Integer id) {
        int i = foodService.delFoodById(id);
        if (i == 1 ) {
            return ResultDTO.success();
        }else {
            return ResultDTO.erro();
        }
    }

    //修改食品
    @PostMapping("/update")
    public ResultDTO updateFood(@RequestBody Food food) {

        foodService.updateFood(food);

        return ResultDTO.success();
    }

    //分页
    @GetMapping("/getByPage")
    public ResultDTO getByPage(@RequestParam String foodName, @RequestParam(defaultValue = "0") Integer foodType,
                               @RequestParam Integer page,@RequestParam Integer size) {

        Map<String, Object> params = new HashMap<>();
        params.put("page", (page-1)*size);
        params.put("size", size);
        params.put("foodName", foodName);
        params.put("foodType", foodType);

        List<Food> byPage = foodService.getByPage(params);

        Page<Food> foodPage = new Page<>();

        long total = foodService.getTotal(foodName, foodType);
        foodPage.setRows(byPage);
        foodPage.setTotal(total);
        foodPage.setPageNum(page);
        foodPage.setPageSize(size);

        return ResultDTO.success(foodPage);
    }

    @PostMapping("/recommendList")
    public ResultDTO recommendList(){

        List<OrderItem> orderItemList = orderItemService.selectAll();
        Map<Integer, Integer> collect = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getFoodId, Collectors.summingInt(OrderItem::getFoodCount)));
        Integer key = collect.entrySet().stream()
                .max(Comparator.comparing(Map.Entry::getValue))
                .orElse(null).getKey();
        Food food = foodService.selectFoodById(key);
//        Map<String,List<Long>> result = studentList.stream().collect(Collectors.groupingBy(Student::getStudentClazzCode,Collectors.mapping(Student::getStudentId,Collectors.toList()));

//
        return ResultDTO.success(food);
    }


}
